package servlet;

import org.apache.commons.codec.digest.DigestUtils;
import pojo.Tuser;
import pojo.TuserAddress;
import service.Impl.TuserAddressServiceImpl;
import service.Impl.TuserServiceImpl;
import service.TuserAddressService;
import service.TuserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/*")
public class TuserServlet extends HttpServlet {

    TuserService tuser = new TuserServiceImpl();
    TuserAddressService  ta = new TuserAddressServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        //获取路径
        String rURI = request.getRequestURI();
        //拆分字符串截取路径
        String[] split = rURI.split("/");
        String ss = split[split.length - 1];
        //细分
        String[] split1 = ss.split("\\?");
        String s = split1[0];
        if ("login".equals(s)) {
            this.login(request, response);
        } else if ("address".equals(s)){
            this.address(request,response);
        }
    }

    private void address(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Tuser user = (Tuser) session.getAttribute("user");
        String address = request.getParameter("address");
        String remark = request.getParameter("remark");
        ta.insaddress(new TuserAddress(0,user.getId(),address,null,"0",remark));
        response.getWriter().print("true");
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        //进行md5加密匹配
        password = DigestUtils.md5Hex(password);
        Tuser login = tuser.login(account, password);
        HttpSession session = request.getSession();
        PrintWriter writer = response.getWriter();
        if (login != null) {
            session.setAttribute("user", login);
            writer.print("<script>\n" +
                    "    location.href = \"/index.jsp\";\n" +
                    "    alert(\"登录成功!\");\n" +
                    "</script>");
        } else {
            writer.print("<script>\n" +
                    "    location.href = \"/login.jsp\";\n" +
                    "    alert(\"登录失败!\");\n" +
                    "</script>");
        }

    }
}
